/**
 * Class to manage the application of stamps to PDF documents
 */
package us.gaaoc.framework.signature.visual;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.security.cert.CertPath;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

import javax.faces.context.FacesContext;

import org.apache.log4j.Logger;
import org.jfree.util.Log;

import us.gaaoc.framework.dao.persistenceLogic.BaseDataAccessor;
import us.gaaoc.framework.model.Court;
import us.gaaoc.framework.model.DocumentStatus;
import us.gaaoc.framework.model.Documents;
import us.gaaoc.framework.model.LdapDirectoryPerson;
import us.gaaoc.framework.model.Person;
import us.gaaoc.framework.model.SignatureImage;
import us.gaaoc.framework.model.VisualMark;
import us.gaaoc.framework.model.VisualMarkCategory;
import us.gaaoc.framework.signature.digital.SignatureValidator;
import us.gaaoc.framework.signature.digital.ldap.LdapClient;
import us.gaaoc.framework.util.DateUtil;
import us.gaaoc.framework.util.pdf.regexp.DocumentRegexps;
import us.gaaoc.framework.util.pdf.regexp.PDFRegexp;
import us.gaaoc.framework.util.pdf.regexp.PDFRegexpException;

import com.lowagie.text.BadElementException;
import com.lowagie.text.Image;
import com.lowagie.text.pdf.PdfReader;

/**
 * Class to manage the application of stamps to PDF documents
 * 
 */
@SuppressWarnings( { "unchecked", "unused" })
public class PDFStamperController extends BaseDataAccessor {

	private static final Logger LOG = Logger
			.getLogger(PDFStamperController.class);
	private String signatureTrackingID;
	private PDFStamper pdfStamper = new PDFStamper();
	private boolean signedDoc;
	private boolean stampedDoc;
	private boolean docketIDStamped;

	/**
	 * @return the signedDoc
	 */
	public boolean isSignedDoc() {
		return signedDoc;
	}

	/**
	 * @param signedDoc
	 *            the signedDoc to set
	 */
	public void setSignedDoc(boolean signedDoc) {
		this.signedDoc = signedDoc;
	}

	/**
	 * @return the stampedDoc
	 */
	public boolean isStampedDoc() {
		return stampedDoc;
	}

	/**
	 * @param stampedDoc
	 *            the stampedDoc to set
	 */
	public void setStampedDoc(boolean stampedDoc) {
		this.stampedDoc = stampedDoc;
	}
	
	/**
	 * Searches the contents of a PDF for a string
	 * @param regex The regular expression used for searching
	 * @param contents the bytes of the PDF
	 * @return true if found, false if not found
	 */
	public boolean checkPDFForString(String regex, byte[] contents)
	{
		String s = new String(contents);
		
		if(s.matches(regex))
			return true;
		else
			return false;
	}

	/**
	 * Method to apply a Court Received Stamp to Filed Documents
	 * 
	 * @param documentListPassed
	 *            List of Documents to process
	 * @param datePassed
	 *            Date to use for stamping the document
	 * @param personSigner
	 *            Person to use for signature indicator
	 * @param courtFiledIntoUuidPassed
	 *            Uuid of the court being filed into
	 * @return List of documents modified with Court Received stamps applied
	 */
	public List<Documents> applyCourtReceivedStamp(
			List<Documents> documentListPassed, Date datePassed,
			Person personSigner, String courtFiledIntoUuidPassed) {
		
		System.out.println("Ready to apply the stamp");

		LdapDirectoryPerson ldapPerson = this.getModelFacade()
				.findLdapDirectoryByPerson(personSigner);
		String cnName = ldapPerson.getCname();
		//To get Fulton Court Stamp
/*		if (cnName.equalsIgnoreCase("Arleatha Mckenzie") || cnName.equalsIgnoreCase("Bandele Browne")
				|| cnName.equalsIgnoreCase("Al Clark") || cnName.equalsIgnoreCase("Monical Smith")) {*/
		if (courtFiledIntoUuidPassed.equalsIgnoreCase("courtUuid4")) {
			cnName = "Fulton Stamp";
		}
		LdapClient ldapClient = new LdapClient();
		Image sigIndicatorImage = ldapClient.retrieveSignatureImage(cnName);
		String doctype = "";

		if (documentListPassed != null && !documentListPassed.isEmpty()) {
			int documentInstanceCode;
			String docLocalCode;

			int docStatusCode;
			for (Documents doc : documentListPassed) {
				
				if(checkPDFForString(DocumentRegexps.getCourtRegexp(courtFiledIntoUuidPassed,
						DocumentRegexps.FIND_COURT_STAMP), doc.getContent())){
					this.setStampedDoc(true);
					continue;
				}
				
				int docTypeCode = doc.getDocumentInstance().getDocumentType()
						.getCode();
				docLocalCode = doc.getDocumentInstance().getDocLocalCode().getCode();
				if (((docTypeCode == 30034) || (docTypeCode == 30027))
						&& courtFiledIntoUuidPassed.equalsIgnoreCase("courtUuidBibb")
					||
						(docLocalCode.equalsIgnoreCase("129331"))) // we don't stamp the sherriff entry of service when it is not served.
						
				{
					// don't stamp with court received stamp but stamped
					this.setStampedDoc(true);
				} else {

					if ((!((courtFiledIntoUuidPassed
							.equalsIgnoreCase("courtUuidBibb")) && ((docTypeCode == 30034) || (docTypeCode == 30027))))
							&& !((courtFiledIntoUuidPassed
									.equalsIgnoreCase("courtUuidHart")) && ((docTypeCode == 34) || docTypeCode == 27))

					) {
						documentInstanceCode = doc.getDocumentInstance()
								.getCode();
						// Set document type variable
						doctype = doc.getDocumentInstance().getCode() + "";
						byte[] originalDocContent = doc.getContent();
						docStatusCode = doc.getStatus().getCode();
						if (doc.getContent() != null) {
							// if doc is not ready to be imported and is not
							// already
							// court received stamped
							if ((docStatusCode != 7) // Prepared for Import
									&& (docStatusCode != 9)) { // Stamped with
								// court received
								// stamp
								if (documentInstanceCode != 300181) { // Sheriff's
									// Entry of
									// Service -
									// Filed - Bibb

									// Add Clerk Stamp on the first page of each
									// PDF
									// document
									System.out.println("The pdf document "
											+ doc.getTitle()
											+ " A stamp can be applied");

									int visualCategoryCode = 3; // court stamp
									boolean defaultCourtStampFlag = true;
									VisualMarkCategory visualMarkCategory = this
											.getModelFacade()
											.getVisualCategory(
													visualCategoryCode);
									VisualMark visualMark = this
											.getModelFacade().getVisualMark(
													personSigner,
													defaultCourtStampFlag,
													visualMarkCategory);

									String courtStampTarget = visualMark
											.getVisualTarget();
									byte[] newDocContent = pdfStamper
											.AddCourtStamp(doc,
													sigIndicatorImage,
													datePassed,
													courtFiledIntoUuidPassed,
													courtStampTarget);
									if (newDocContent != null) {
										doc.setContent(personSigner,newDocContent);
										this.setStampedDoc(true);
									} else {
										this.setStampedDoc(false);
										/*
										 * doc.setContent(originalDocContent);
										 * DocumentStatus ds = new
										 * DocumentStatus(); ds.setCode(12);
										 * ds.setDescription
										 * ("failedCourtReceivedStamp");
										 * doc.setStatus(ds);
										 */
										break;
									}
								}
							}
						}
					}
				}
			}

		}
		// FOR DEBUGGING PURPOSES ONLY. When executing the application comment
		// out five lines below
		/*
		 * DocumentStatus ds = new DocumentStatus(); ds.setCode(12);
		 * ds.setDescription("failedCourtReceivedStamp");
		 * documentList.get(2).setStatus(ds); documentList.get(1).setStatus(ds);
		 */
		return documentListPassed;

	}

	/**
	 * Method to apply a Docket Number/Court Case Number/Civil Action File
	 * Number to a list of PDF documents
	 * 
	 * @param documentListPassed
	 *            List of PDF's to process
	 * @param docketIDPassed
	 *            Number to use for stamping process
	 * @param personSigner
	 * @return List of documents with stamp applied.
	 */
	public List<Documents> applyDocketIdStamp(
			List<Documents> documentListPassed, String docketIDPassed,
			Person personSigner) {
		if (documentListPassed != null && !documentListPassed.isEmpty()) {
			int documentType;
			byte[] documentContent = null;
			for (Documents doc : documentListPassed) {

				if(checkPDFForString(DocumentRegexps.getCourtRegexp(doc.getCaseRecord().getCourt(),
						DocumentRegexps.FIND_CVNUMVER_STAMP), doc.getContent())){
					this.setDocketIDStamped(true);
					continue;
				}
				
				documentType = doc.getDocumentInstance().getDocumentType()
						.getCode();

				// TODO the exclusion of the documentsInstances must be done
				// dynamically
				// otherwise we have to hard code every added county's files
				// that must be excluded

				documentContent = this.applyDocketIdStampOnOneDoc(doc,
						docketIDPassed, personSigner);

				// If document content is null and the document
				// is not a Child Support Worksheet on File
				// (Type Code 5), then signal an error
				// condition.
				if (documentContent == null && documentType != 5) {
					this.setDocketIDStamped(false);
					return documentListPassed;
				} else {
					this.setDocketIDStamped(true);
				}

			}
		}
		return documentListPassed;
	}

	/**
	 * @param docketIDStamped
	 */
	private void setDocketIDStamped(boolean docketIDStamped) {
		this.docketIDStamped = docketIDStamped;

	}

	/**
	 * @return the docketIDStamped
	 */
	public boolean isDocketIDStamped() {
		return docketIDStamped;
	}

	public byte[] applyDocketIdStampOnOneDoc(Documents doc,
			String docketIDPassed, Person personSigner) {

		// int documentType =
		// doc.getDocumentInstance().getDocumentType().getCode();
		// TODO the exclusion of the documentsInstances must be done dynamically
		// otherwise we have to hard code every added county's files that must
		// be excluded

		byte[] returnContent = null;

		returnContent = pdfStamper.addVisualDocketID(doc, docketIDPassed);
		if (returnContent == null) {
			/*
			 * this.setStampedDoc(false); doc.setContent(docContent);
			 * DocumentStatus ds = new DocumentStatus();
			 * this.getModelFacade().findDocumentStatus(13);
			 * //failedCourtReceivedStamp doc.setStatus(ds);
			 */
			return returnContent;
		}else {
			this.setStampedDoc(true);
			doc.setContent(personSigner,returnContent);
			DocumentStatus ds = new DocumentStatus();
			ds = this.getModelFacade().findDocumentStatus(10); // stampedWithCivilActionNumberStamp
			doc.setStatus(ds);
		}
		/*
		int visualCategoryCode = 5; // for Docket ID
		VisualMarkCategory visualCategory = this.getModelFacade()
				.getVisualCategory(visualCategoryCode);
		VisualMark visualMark = this.getModelFacade().getVisualMark(
				personSigner, altSigFlag, visualCategory);

		List<String> targetForDocketList = new ArrayList<String>();
		List<VisualMark> visualMarkList = new ArrayList<VisualMark>();
		// to get alternate targets set altSigFlag = false
		visualMarkList = this.getModelFacade().getVisualMarkList(personSigner,
				false, visualCategory);

		String tempTarget = "";
		for (VisualMark vm : visualMarkList) {
			tempTarget = vm.getVisualTarget();
			targetForDocketList.add(tempTarget);
		}
		caseNumberTarget = visualMark.getVisualTarget();
		returnContent = pdfStamper.addVisualDocketID(doc, caseNumberTarget,
				docketIDPassed);
		if (returnContent == null) {
			for (String targetForSigFromList : targetForDocketList) {
				returnContent = pdfStamper.addVisualDocketID(doc,
						targetForSigFromList, docketIDPassed);
				if (returnContent != null)
					break;
			}
		}

		if (returnContent == null) {
			/*
			 * this.setStampedDoc(false); doc.setContent(docContent);
			 * DocumentStatus ds = new DocumentStatus();
			 * this.getModelFacade().findDocumentStatus(13);
			 * //failedCourtReceivedStamp doc.setStatus(ds);
			 
			return returnContent;

		} else if (returnContent != null) {
			this.setStampedDoc(true);
			doc.setContent(returnContent);
			DocumentStatus ds = new DocumentStatus();
			ds = this.getModelFacade().findDocumentStatus(10); // stampedWithCivilActionNumberStamp
			doc.setStatus(ds);
		}
		*/

		return returnContent;
	}

	/**
	 * @param doc
	 * @param personSignerPassedIn
	 * @param roleUuid
	 */
	//public void addVisualSignatureOnDocument(Documents doc,	Person personSignerPassedIn, LdapDirectoryPerson ldPerson,String roleUuid) {
	public void addVisualSignatureOnDocument(Documents doc,	Person personSignerPassedIn,String roleUuid) {

		String clerkRoleUuid = "uuid2"; // The Clerk Role UUID
		String attorneyRoleUuid = "uuid6"; // The Attorney Role UUID
		String agentRoleUuid = "uuid5"; // The Agent Role UUID
		LOG.debug("Entered PDFStamperController");
		
		if (doc == null)
			LOG.debug("nothing in Documents");
		
		byte[] docContent = doc.getContent();
		LOG.debug("docContent.length == "+docContent.length);
		if (docContent.length == 0) {
			LOG.info("The pdf file has no contents to apply a signature image"
					+ " to.");
			doc.setSignedDoc(false);
			if (roleUuid.equalsIgnoreCase(clerkRoleUuid)) {
				DocumentStatus ds = new DocumentStatus();
				ds.setCode(14);
				ds.setDescription("failedClerkSignature");
				doc.setStatus(ds);
			} else if (roleUuid.equalsIgnoreCase(attorneyRoleUuid)) {
				DocumentStatus ds = new DocumentStatus();
				ds.setCode(15);
				
				ds.setDescription("failedAttorneySignature");
				LOG.error("Attorney Sign failed"); /*brownb*/
				doc.setStatus(ds);
			}
			
			else if (roleUuid.equalsIgnoreCase(agentRoleUuid)) {
				DocumentStatus ds = new DocumentStatus();
				ds.setCode(17);
				ds.setDescription("Agent Sign failed");
				doc.setStatus(ds);
			}
			return;
		}
		/*
		 * Retrieve the certificate password
		 */
		//String cnName = ldPerson.getCname();

		//LdapClient ldapClient = new LdapClient();
		Image image = null;
		image = this.retrieveSignatureImageFromDB(personSignerPassedIn.getUuid());
		if (image.isJpeg()) {
			//image = ldapClient.retrieveSignatureImage(cnName);
			LOG.info("SuccessFully Retrieved the image");

		} else {
			// If no connection to LDAP, don't even try to add signature image
			// to
			// document.
			LOG.info("Error retrieving signature indicator image from LDAP.");
			LOG.error("Error retrieving signature indicator image from LDAP.");
			doc.setSignedDoc(false);
			if (roleUuid.equalsIgnoreCase(clerkRoleUuid)) {
				DocumentStatus ds = new DocumentStatus();
				ds.setCode(14);
				LOG.error("Signature Failed because the clerk is not in LDAP");
				ds.setDescription("failedClerkSignature");
				doc.setStatus(ds);
			} else if (roleUuid.equalsIgnoreCase(attorneyRoleUuid)) {
				DocumentStatus ds = new DocumentStatus();
				ds.setCode(15);
				LOG.error("Signature Failed because the attorney is not in LDAP"); //Added Code brownb
				ds.setDescription("failedAttorneySignature");
				doc.setStatus(ds);
			}else if (roleUuid.equalsIgnoreCase(attorneyRoleUuid)) {
				DocumentStatus ds = new DocumentStatus();
				ds.setCode(17);
				LOG.error("Signature Failed because the agent is not in LDAP"); //Added Code brownb
				ds.setDescription("failedAgentSignature");
				doc.setStatus(ds);
			}
			return;
		}

		// If no image retrieved, then don't try to sign.
		if (image != null) {

			String targetForSig = "";
			boolean altSigFlag = true; // to find default signature target
			int visualCategoryCode = 1; // for the signature
			VisualMarkCategory visualCategory = this.getModelFacade()
					.getVisualCategory(visualCategoryCode);
			VisualMark visualMark = this.getModelFacade().getVisualMark(
					personSignerPassedIn, altSigFlag, visualCategory);

			List<String> targetForSigList = new ArrayList<String>();
			List<VisualMark> visualMarkList = new ArrayList<VisualMark>();
			visualMarkList = this.getModelFacade().getVisualMarkList(
					personSignerPassedIn, false, visualCategory);

			String tempTarget = "";
			for (VisualMark vm : visualMarkList) {
				tempTarget = vm.getVisualTarget();
				targetForSigList.add(tempTarget);
			}
			targetForSig = visualMark.getVisualTarget();
			// TODO: get the current courtUuid from session
			String courtUuid = visualMark.getPerson().getOrganizations().get(0)
					.getCourtUuid();

			byte[] tempDocContents = pdfStamper.addVisualSignatureIndicator(
					doc, image, personSignerPassedIn, targetForSig);
			if (tempDocContents == null) {
				for (String targetForSigFromList : targetForSigList) {
					tempDocContents = pdfStamper.addVisualSignatureIndicator(
							doc, image, personSignerPassedIn,
							targetForSigFromList);
					if (tempDocContents != null)
						break;

				}
			}

			// FOR DEBUGGING PURPOSES ONLY. When running the application
			// uncomment
			// the line below
			// tempDocContents = null;
			// FOR DEBUGGING PURPOSES ONLY. When running the application
			// uncomment
			// the four lines below
			/*
			 * CaseRecordStatus crs = new CaseRecordStatus(); crs.setCode(1);
			 * crs.setDescription("Received");
			 * docPassedIn.getCaseRecord().setStatus(crs);
			 */
			if (tempDocContents == null) {
				LOG
						.info("Error applying visual signature indicator image . . .");
				this.setSignedDoc(false);
				if (roleUuid.equalsIgnoreCase(clerkRoleUuid)) {
					DocumentStatus ds = new DocumentStatus();
					ds.setCode(14);
					ds.setDescription("failedClerkSignature");
					doc.setStatus(ds);
				} else if (roleUuid.equalsIgnoreCase(attorneyRoleUuid)) {
					DocumentStatus ds = new DocumentStatus();
					ds.setCode(15);
					ds.setDescription("failedAttorneySignature");
					doc.setStatus(ds);
				}
				else if (roleUuid.equalsIgnoreCase(agentRoleUuid)) {
					DocumentStatus ds = new DocumentStatus();
					ds.setCode(17);
					ds.setDescription("Agent Sign failed");
					doc.setStatus(ds);
				}
				return;
			} else if (tempDocContents != null) {
				doc.setContent(personSignerPassedIn,tempDocContents);
				this.setSignedDoc(true);
				if (roleUuid.equalsIgnoreCase(clerkRoleUuid)) {
					DocumentStatus ds = new DocumentStatus();
					ds.setCode(8);
					ds.setDescription("signedByClerk");
					doc.setStatus(ds);
				} else if (roleUuid.equalsIgnoreCase(attorneyRoleUuid)) {
					DocumentStatus ds = new DocumentStatus();
					ds.setCode(11);
					ds.setDescription("signedByAttorney");
					doc.setStatus(ds);
				}else if (roleUuid.equalsIgnoreCase(agentRoleUuid)) {
					DocumentStatus ds = new DocumentStatus();
					ds.setCode(18);
					ds.setDescription("signedByAgent");
					doc.setStatus(ds);
					System.out.println("Yes since all went well in the addVisualSignatureOnDocument method the Document Status has been set to 18 meaning signed By Agent and isSignedDoc is set to" + isSignedDoc());

				}

				// add the signature date after signing the document.
				System.out.println("[SIGN_DATE] Adding SIGN_DATE on " + (pdfStamper.getStampedSignPage()-1));
				this.addSignDateOnDocument(doc, personSignerPassedIn, roleUuid,pdfStamper.getStampedSignPage()-1);
				// this.addCourtDateOnDocument(doc, personSignerPassedIn,
				// roleUuid, courtUuid);
				// this.addCourtNumberOnDocument(doc, personSignerPassedIn,
				// roleUuid, courtUuid);
				// this.addCourtTimeOnDocument(doc,personSignerPassedIn,
				// roleUuid,courtUuid);
				
				if(courtUuid.equalsIgnoreCase("courtUuidAugustaRichmond") && roleUuid.equalsIgnoreCase(attorneyRoleUuid))
				{
					LOG.info("The BARID is only placed on a document only if the Document is to be signed by the attorney");

					this.addBarIDStampOnDocument(doc, personSignerPassedIn, roleUuid,pdfStamper.getStampedSignPage()-1);
				}
				
				
			}

		} else {
			LOG.info("Error retrieving visual signature indicator image . . .");
			this.setSignedDoc(false);
			// doc.setContent(docContent);
			if (roleUuid.equalsIgnoreCase(clerkRoleUuid)) {
				DocumentStatus ds = new DocumentStatus();
				ds.setCode(14);
				ds.setDescription("failedClerkSignature");
				doc.setStatus(ds);
			} else if (roleUuid.equalsIgnoreCase(attorneyRoleUuid)) {
				DocumentStatus ds = new DocumentStatus();
				ds.setCode(15);
				ds.setDescription("failedAttorneySignature");
				doc.setStatus(ds);
			}
			
			else if (roleUuid.equalsIgnoreCase(agentRoleUuid)) {
				DocumentStatus ds = new DocumentStatus();
				ds.setCode(17);
				ds.setDescription("Agent Sign failed");
				doc.setStatus(ds);
			}
			return;
		}

	}

	/**
	 * @param doc
	 * @param personSigner
	 * @param roleUuid
	 */
	private void addSignDateOnDocument(Documents doc, Person personSigner,
			String roleUuid,int onPage) {
		
		TimeZone tz = TimeZone.getTimeZone("America/New_York");
		GregorianCalendar calendar = new GregorianCalendar(tz);
		String courtUuid = (String) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("courtUuid");
		
		String regexp = DocumentRegexps.getRegexp(doc.getDocumentInstance().getCode(),DocumentRegexps.SIGN_DATE);		
		if(regexp == null)
		{
			LOG.info("ERROR Couldn't get regexp sign date for document : " 
					+ Integer.toString(doc.getDocumentInstance().getCode()) + " uuid : " +
					doc.getUuid());
		}else{
		
			Map<String,String> targets  = new java.util.HashMap<String,String>();
			
			targets.put("SIGN_DAY",Integer.toString(calendar.get(Calendar.DAY_OF_MONTH)));
			targets.put("SIGN_MONTH_YEAR",
					calendar.getDisplayName(Calendar.MONTH,Calendar.LONG,java.util.Locale.ENGLISH) + ", " +
					Integer.toString(calendar.get(Calendar.YEAR)).substring(0, 4));
			LOG.debug("targets= "+targets+" regexp= "+regexp+ " onPage= "+onPage);
		
			try {
				applyRegexpOnDocument(doc,personSigner,roleUuid,doc.getCaseRecord().getCourtUuid(),targets,regexp,onPage);
				targets.clear();
				return;
			} catch (PDFRegexpException e) {
				e.printStackTrace();
				LOG.info("ERROR Regexp sign date failed for document " 
						+ Integer.toString(doc.getDocumentInstance().getCode()) + " uuid : " +
						doc.getUuid());
			}
		}
		
		/*
		 * check the document instance code for the document and then add the
		 * date on the document
		 */
		// to save the original contents into the documents if it is failed
		byte[] originalDocContent = doc.getContent();
		int documentInstanceCode = doc.getDocumentInstance().getCode();
		String clerkRoleUuid = "uuid2"; // The Clerk Role UUID
		String judgeRoleUuid = "uuid4"; // The Judge Role UUID
		String attorneyRoleUuid = "uuid6"; // The Attorney Role UUID
		String agentRoleUuid = "uuid5"; // The Attorney Role UUID

		/*
		 * TODO !!! Need to make this document list dynamic. Missing several
		 * documents from Washington County. Needs to be able to be pulled from
		 * the database to be able to be added to and removed from as needed.
		 * !!!
		 */

		if (!(documentInstanceCode == 105) && !(documentInstanceCode == 109)
				&& !(documentInstanceCode == 119)
				&& !(documentInstanceCode == 126)
				&& !(documentInstanceCode == 132)
				&& !(documentInstanceCode == 159)
				&& !(documentInstanceCode == 161)
				&& !(documentInstanceCode == 166)
				&& !(documentInstanceCode == 53)
				&& !(documentInstanceCode == 54)
				&& !(documentInstanceCode == 125) // Complaint Petition for
				// Support - CAF -
				// Washington
				&& !(documentInstanceCode == 114)) { // Motion for Contempt -
			// Washington

			boolean defaultDateFlag = true;
			int visualCategoryCode_signDate = 4; // for sign date

			VisualMarkCategory visualMarkCategory = this.getModelFacade()
					.getVisualCategory(visualCategoryCode_signDate);
			VisualMark visualMark_signDate = this.getModelFacade()
					.getVisualMark(personSigner, defaultDateFlag,
							visualMarkCategory);
			List<VisualMark> visualMark_signDate_List = new ArrayList<VisualMark>();
			String target_signDate = "";
			List<String> target_signDate_List = new ArrayList<String>();

/* FJ Commented out on 1/14/2009			boolean specialFormat = false;
			
			//TODO: move this into an association table between VisualMark and DocumentInstance
			/*
			if(doc.getDocumentInstance().getCode() == 1441)
			{
				//oglethorpes rule nisi
				visualMark_signDate = (VisualMark) HibernatePhaseListener.getSessionFactory().getCurrentSession().get(VisualMark.class, "VisualMarkUuidOgleRuleNisi");
				if (visualMark_signDate != null) {
					target_signDate = visualMark_signDate.getVisualTarget().replaceAll("\\+", "");
					specialFormat = true;
				}
			}
			else if (doc.getDocumentInstance().getCode() == 1196 || doc.getDocumentInstance().getCode() == 1197)
			{
				//oglethorpe complaint petition
				visualMark_signDate = (VisualMark) HibernatePhaseListener.getSessionFactory().getCurrentSession().get(VisualMark.class, "VisualMarkUuidOgleComplaintPetition");
				if (visualMark_signDate != null) {
					target_signDate = visualMark_signDate.getVisualTarget().replaceAll("\\+","");
					specialFormat = true;
				}
			}else{			
					target_signDate = visualMark_signDate.getVisualTarget().replaceAll("\\+","");
				specialFormat = true;
			
			}else{		
				target_signDate = visualMark_signDate.getVisualTarget();
				specialFormat = false;	
			}
*/
			//}
			

		    //defaultDateFlag = true;
		//FJ	visualMark_signDate_List = this.getModelFacade().getVisualMarkList(
		//FJ			personSigner, false, visualMarkCategory);
			visualMark_signDate_List = this.getModelFacade().getVisualMarkList(
					personSigner, true, visualMarkCategory);
			for (VisualMark vm : visualMark_signDate_List) {
		//FJ		String tempTarget_signDate = vm.getVisualTarget();
		//FJ		target_signDate_List.add(tempTarget_signDate);
				target_signDate = vm.getVisualTarget();
				target_signDate_List.add(target_signDate);
			}

			byte[] tempSignedDocContents = pdfStamper.addSignDate(doc,
					visualMark_signDate,
					target_signDate, roleUuid);

			if (tempSignedDocContents == null) {
				for (String targetForSig : target_signDate_List) {
					tempSignedDocContents = pdfStamper.addSignDate(doc,
							visualMark_signDate,
							targetForSig, roleUuid);
					if (tempSignedDocContents != null)
						break;
				}
			}
			if (tempSignedDocContents == null) {
				LOG.info("Error applying Signed-On Date stamp . . .");
			} else {
				doc.setContent(personSigner,tempSignedDocContents);
			}
			// TODO Need to re-enable the section below once a better list of
			// documents that have "Signed-on" date lines is known.
			// It is commented out due to missing too many at the current time
			// and causing errors in signing for Washington County.
			/*
			 * this.setSignedDoc(false); if
			 * (roleUuid.equalsIgnoreCase(clerkRoleUuid)) { DocumentStatus ds =
			 * new DocumentStatus(); ds.setCode(14);
			 * ds.setDescription("failedClerkSignature"); doc.setStatus(ds); }
			 * else if (roleUuid.equalsIgnoreCase(attorneyRoleUuid)) {
			 * DocumentStatus ds = new DocumentStatus(); ds.setCode(15);
			 * ds.setDescription("failedAttorneySignature"); doc.setStatus(ds);
			 * } } else {
			 */
			/*
			 * this.setSignedDoc(true); if
			 * (roleUuid.equalsIgnoreCase(clerkRoleUuid)) { DocumentStatus ds =
			 * new DocumentStatus(); ds.setCode(8);
			 * ds.setDescription("signedByClerk"); doc.setStatus(ds); } else if
			 * (roleUuid.equalsIgnoreCase(attorneyRoleUuid)) { DocumentStatus ds
			 * = new DocumentStatus(); ds.setCode(11);
			 * ds.setDescription("signedByAttorney"); doc.setStatus(ds); } }
			 */
		}

	}
	
	
	private void addBarIDStampOnDocument(Documents doc, Person personSigner,String roleUuid,int onPage)
	{		
		
		String courtUuid = (String) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("courtUuid");
		Court court = this.getModelFacade().findCourt(courtUuid);
		String barID = this.getModelFacade().getBarID(personSigner, court);

		String regexp = DocumentRegexps.getRegexp(doc.getDocumentInstance().getCode(),DocumentRegexps.BARID_STAMP);		
		if(regexp == null)
		{
			LOG.error("ERROR Couldn't get regexp Bar ID stamp for document : " 
					+ Integer.toString(doc.getDocumentInstance().getCode()) + " uuid : " +	doc.getUuid());
		}else{
		
			Map<String,String> targets  = new java.util.HashMap<String,String>();
			
			targets.put("BARID",barID);
			
			
		
			try {
				applyRegexpOnDocument(doc,personSigner,roleUuid,doc.getCaseRecord().getCourtUuid(),targets,regexp,onPage);
				return;
			} catch (PDFRegexpException e) {
				e.printStackTrace();
				LOG.error("ERROR Regexp Bar ID failed for document " 
						+ Integer.toString(doc.getDocumentInstance().getCode()) + " uuid : " +
						doc.getUuid());
			}
		}
		
		/*
		 * check the document instance code for the document and then add the
		 * date on the document
		 */
		// to save the original contents into the documents if it is failed
		byte[] originalDocContent = doc.getContent();
		int documentInstanceCode = doc.getDocumentInstance().getCode();
		String clerkRoleUuid = "uuid2"; // The Clerk Role UUID
		String judgeRoleUuid = "uuid4"; // The Judge Role UUID
		String attorneyRoleUuid = "uuid6"; // The Attorney Role UUID

		/*
		 * TODO !!! Need to make this document list dynamic. Missing several
		 * documents from Washington County. Needs to be able to be pulled from
		 * the database to be able to be added to and removed from as needed.
		 * !!!
		 */

		if (!(documentInstanceCode == 105) && !(documentInstanceCode == 109)
				&& !(documentInstanceCode == 119)
				&& !(documentInstanceCode == 126)
				&& !(documentInstanceCode == 132)
				&& !(documentInstanceCode == 159)
				&& !(documentInstanceCode == 161)
				&& !(documentInstanceCode == 166)
				&& !(documentInstanceCode == 53)
				&& !(documentInstanceCode == 54)
				&& !(documentInstanceCode == 125) // Complaint Petition for
				// Support - CAF -
				// Washington
				&& !(documentInstanceCode == 114)) { // Motion for Contempt -
			// Washington

			boolean defaultDateFlag = true;
			int visualCategoryCode_BarIdStamp =11; // for Bar ID

			VisualMarkCategory visualMarkCategory = this.getModelFacade().getVisualCategory(visualCategoryCode_BarIdStamp);
			VisualMark visualMark_BarIdStamp = this.getModelFacade().getVisualMark(personSigner, defaultDateFlag,visualMarkCategory);
			List<VisualMark> visualMark_BarIdStamp_List = new ArrayList<VisualMark>();
			String target_BarIdStamp = "";
			List<String> target_BarIdStamp_List = new ArrayList<String>();


			

	
			visualMark_BarIdStamp_List = this.getModelFacade().getVisualMarkList(personSigner, true, visualMarkCategory);
			for (VisualMark vm : visualMark_BarIdStamp_List) {

				target_BarIdStamp = vm.getVisualTarget();
				target_BarIdStamp_List.add(target_BarIdStamp);
			}
			// Jogi has commented this
		/*	byte[] tempSignedDocContents = pdfStamper.addSignDate(doc,visualMark_BarIdStamp,target_BarIdStamp, roleUuid);

			if (tempSignedDocContents == null) {
				for (String targetForSig : target_BarIdStamp_List) {
					tempSignedDocContents = pdfStamper.addSignDate(doc,visualMark_BarIdStamp,targetForSig, roleUuid);
					if (tempSignedDocContents != null)
						break;
				}
			}
			if (tempSignedDocContents == null) {
				LOG.info("Error applying Signed-On Date stamp . . .");
			} else {
				doc.setContent(tempSignedDocContents);
			}
		*/
		}

	
	}
	
	
	public void addCourtDateOnDocument(Documents doc, Person personSigner,
			String roleUuid,String courtUuid,Date courtDate) throws PDFRegexpException
	{
			if(courtUuid.equalsIgnoreCase("courtUuid3"))
			{
				String regexp = DocumentRegexps.getRegexp(doc.getDocumentInstance().getCode(),DocumentRegexps.COURT_DATE);		
				if(regexp == null)
				{
					LOG.error("ERROR Couldn't get regexp for document : " + Integer.toString(doc.getDocumentInstance().getCode()));
					return;
				}
				
				Map<String,String> targets  = new java.util.HashMap<String,String>();
				Calendar cal = new GregorianCalendar();
				cal.setTime(courtDate);
				
				targets.put("COURT_DAY",Integer.toString(cal.get(Calendar.DAY_OF_MONTH)));
				targets.put("COURT_MONTH_YEAR",
						cal.getDisplayName(Calendar.MONTH,Calendar.LONG,java.util.Locale.ENGLISH) + ", " +
						Integer.toString(cal.get(Calendar.YEAR)).substring(0, 4));
				
				applyRegexpOnDocument(doc,personSigner,roleUuid,courtUuid,targets,regexp,-1);
			}else{
			//	addCourtMonthOnDocument(doc,personSigner,roleUuid,courtUuid,courtDate);
			//	addCourtDayOnDocument(doc,personSigner,roleUuid,courtUuid,courtDate);
			}
			//TODO: Figure out whether the year is going to be on the OCSS documents or not.
	}
	
	/*
	public void addCourtMonthOnDocument(Documents doc, Person personSigner,
			String roleUuid, String courtUuid, Date courtDate) {
		/*
		 * check the document instance code for the document and then add the
		 * date on the document
		 
		// to save the original contents into the documents if it is failed
		byte[] originalDocContent = doc.getContent();
		int documentInstanceCode = doc.getDocumentInstance().getCode();

		if (((documentInstanceCode == 197) || (documentInstanceCode == 196))
				&& courtUuid.equalsIgnoreCase("courtUuid3")) {

			boolean defaultDateFlag = true;
			int visualCategoryCode_signDate = VisualMarkCategoryConstants.COURT_MONTH;

			VisualMarkCategory visualMarkCategory = this.getModelFacade()
					.getVisualCategory(visualCategoryCode_signDate);
			VisualMark visualMark_signDate = this.getModelFacade()
					.getVisualMark(personSigner, defaultDateFlag,
							visualMarkCategory);
			List<VisualMark> visualMark_signDate_List = new ArrayList<VisualMark>();
			String target_signDate = "";
			List<String> target_signDate_List = new ArrayList<String>();

			target_signDate = visualMark_signDate.getVisualTarget();

			// defaultDateFlag = false;
			visualMark_signDate_List = this.getModelFacade().getVisualMarkList(
					personSigner, false, visualMarkCategory);
			for (VisualMark vm : visualMark_signDate_List) {
				String tempTarget_signDate = vm.getVisualTarget();
				target_signDate_List.add(tempTarget_signDate);
			}

			byte[] tempSignedDocContents = pdfStamper.addCourtMonth(doc,
					target_signDate, roleUuid, courtDate);

			if (tempSignedDocContents == null) {
				for (String targetForSig : target_signDate_List) {
					tempSignedDocContents = pdfStamper.addCourtMonth(doc,
							targetForSig, roleUuid, courtDate);
					if (tempSignedDocContents != null)
						break;
				}
			}
			if (tempSignedDocContents == null) {
				LOG.info("Error applying Signed-On Date stamp . . .");
			} else {
				doc.setContent(tempSignedDocContents);
			}
		}

	}
	*/
	/*
	public void addCourtDayOnDocument(Documents doc, Person personSigner,
			String roleUuid, String courtUuid, Date courtDate) {
		/*
		 * check the document instance code for the document and then add the
		 * date on the document
		 
		// to save the original contents into the documents if it is failed
		byte[] originalDocContent = doc.getContent();
		int documentInstanceCode = doc.getDocumentInstance().getCode();

		if (((documentInstanceCode == 197) || (documentInstanceCode == 196))
				&& courtUuid.equalsIgnoreCase("courtUuid3")) {

			boolean defaultDateFlag = true;
			int visualCategoryCode_signDate = VisualMarkCategoryConstants.COURT_DATE_ID;

			VisualMarkCategory visualMarkCategory = this.getModelFacade()
					.getVisualCategory(visualCategoryCode_signDate);
			VisualMark visualMark_signDate = this.getModelFacade()
					.getVisualMark(personSigner, defaultDateFlag,
							visualMarkCategory);
			List<VisualMark> visualMark_signDate_List = new ArrayList<VisualMark>();
			String target_signDate = "";
			List<String> target_signDate_List = new ArrayList<String>();

			target_signDate = visualMark_signDate.getVisualTarget();

			// defaultDateFlag = false;
			visualMark_signDate_List = this.getModelFacade().getVisualMarkList(
					personSigner, false, visualMarkCategory);
			for (VisualMark vm : visualMark_signDate_List) {
				String tempTarget_signDate = vm.getVisualTarget();
				target_signDate_List.add(tempTarget_signDate);
			}

			byte[] tempSignedDocContents = pdfStamper.addCourtDay(doc,
					target_signDate, roleUuid, courtDate);

			if (tempSignedDocContents == null) {
				for (String targetForSig : target_signDate_List) {
					tempSignedDocContents = pdfStamper.addCourtDay(doc,
							targetForSig, roleUuid, courtDate);
					if (tempSignedDocContents != null)
						break;
				}
			}
			if (tempSignedDocContents == null) {
				LOG.info("Error applying Signed-On Date stamp . . .");
			} else {
				doc.setContent(tempSignedDocContents);
			}
		}

	}
	*/

	
	public void applyRegexpOnDocument(Documents doc,Person personSigner, String roleUuid, String courtUuid, Map<String,String> targets,String regexp,int page) throws PDFRegexpException
	{
		byte[] data = doc.getContent();		
		
		try{
			PDFRegexp pdf = new PDFRegexp();
			if(targets.containsKey("BARID"))
			{
				data = pdf.applyRegexp(data, regexp, true, targets,page,page+1);

			}else
			{
				data = pdf.applyRegexp(data, regexp, false, targets,page,page+1);
			}
		}catch(PDFRegexpException exn)
		{	
			LOG.info("Error with PDF regexp : " + exn.getMessage());
			throw exn;
		}catch(Exception exn)
		{			
			LOG.error("Error writing CourtDate on document with REGEXP!");	
			throw new PDFRegexpException(exn);			
		}
		doc.setContent(personSigner,data);
	}
	

	
	public void addCourtNumberOnDocument(Documents doc, Person personSigner,
			String roleUuid, String courtUuid, String courtRoomNumber) throws PDFRegexpException {
		
		
		int documentInstance = doc.getDocumentInstance().getCode();
		
		if( ((documentInstance == 197) || (documentInstance == 196)) && 
				courtUuid.equalsIgnoreCase("courtUuid3"))
		{
			String regexp = DocumentRegexps.getRegexp(documentInstance, DocumentRegexps.COURT_ROOM);
			
			if(regexp == null)
			{
				LOG.error("ERROR Couldn't get regexp for document : " + Integer.toString(doc.getDocumentInstance().getCode()));
				return;
			}
			
			
			Map<String,String> targets = new HashMap<String,String>();
			targets.put("COURT_ROOM",courtRoomNumber);
			applyRegexpOnDocument(doc,personSigner,roleUuid,courtUuid,targets,regexp,-1);
		}
	}
	

	
	public void addCourtTimeOnDocument(Documents doc, Person personSigner,
			String roleUuid, String courtUuid, String courtTime) throws PDFRegexpException {
		
		int documentInstance = doc.getDocumentInstance().getCode();
		
		if( ((documentInstance == 197) || (documentInstance == 196)) && 
				courtUuid.equalsIgnoreCase("courtUuid3"))
		{
			String regexp = DocumentRegexps.getRegexp(documentInstance, DocumentRegexps.COURT_TIME);
			
			if(regexp == null)
			{
				LOG.info("ERROR Couldn't get regexp for document : " + Integer.toString(doc.getDocumentInstance().getCode()));
				return;
			}

			Map<String,String> targets = new HashMap<String,String>();
			targets.put("COURT_TIME",courtTime);
			applyRegexpOnDocument(doc,personSigner,roleUuid,courtUuid,targets,regexp,-1);
		}
	}
	
	
	

	public List<Documents> applyAttorneySignature(
			List<Documents> documentListPassed) {
		List<Documents> documentList = documentListPassed;

		return documentList;
	}

	private String stripOfAllSlashes(String string) {
		String slash = "/";
		if (string.indexOf(slash) != -1) {
			string = string.substring(0, string.indexOf(slash))
					+ string.substring(string.indexOf(slash) + 1);
			if (string.indexOf(slash) != -1) {
				string = string.substring(0, string.indexOf(slash))
						+ string.substring(string.indexOf(slash) + 1);
				return string;
			} else {
				return string;
			}
		} else {
			return string;
		}
	}

	private String stripOfAllNonAlfaNumeric(String string) {
		String space = " ";
		char spChar = space.charAt(0);
		char colonChar = ":".charAt(0);
		char singleQ = "\'".charAt(0);
		string = removeChar(string, spChar);
		string = removeChar(string, colonChar);
		string = removeChar(string, singleQ);

		return string;
	}

	private String removeChar(String s, char c) {
		String r = "";
		for (int i = 0; i < s.length(); i++) {
			if (s.charAt(i) != c)
				r += s.charAt(i);
		}
		return r;
	}

	private X509Certificate getX509Certificate(byte[] certificationChain)
			throws IOException, CertificateException {
		X509Certificate cert = null;
		SignatureValidator validator = new SignatureValidator();
		InputStream in = new ByteArrayInputStream(certificationChain);

		// Read the certificate file and save it into the string
		String certChainBase64Encoded = null;
		BufferedReader br = new BufferedReader(new InputStreamReader(in));
		certChainBase64Encoded = br.readLine();

		CertPath certPath = validator
				.loadCertPathFromBase64String(certChainBase64Encoded);
		List certsInChain = certPath.getCertificates();
		X509Certificate[] X509CertificateChain = (X509Certificate[]) certsInChain
				.toArray(new X509Certificate[0]);
		cert = X509CertificateChain[0];

		return cert;
	}

	/**
	 * @return the signatureTrackingID
	 */
	public String getSignatureTrackingID() {
		return signatureTrackingID;
	}

	/**
	 * @param signatureTrackingID
	 *            the signatureTrackingID to set
	 */
	public void setSignatureTrackingID(String signatureTrackingID) {
		this.signatureTrackingID = signatureTrackingID;
	}

	public void applyCourtReceivedStamp(Documents doc, Date submittedDate,
			Person personSigner, String courtUuid) {
		// TODO Auto-generated method stub
		int documentInstanceCode;
		String doctype;
		int docStatusCode;
		int docTypeCode = doc.getDocumentInstance().getDocumentType().getCode();

		LdapDirectoryPerson ldapPerson = this.getModelFacade()
				.findLdapDirectoryByPerson(personSigner);
		String cnName = ldapPerson.getCname();
		//To get Fulton Court Stamp
		if (cnName.equalsIgnoreCase("Arleatha Mckenzie") || cnName.equalsIgnoreCase("Bandele Browne")
				|| cnName.equalsIgnoreCase("Al Clark") || cnName.equalsIgnoreCase("Monical Smith")) {
			cnName = "Fulton Stamp";
		}
		LdapClient ldapClient = new LdapClient();
		Image sigIndicatorImage = ldapClient.retrieveSignatureImage(cnName);

		if ((docTypeCode == 34) || (docTypeCode == 27)) {
			// don't stamp with court received stamp but stamped
			this.setStampedDoc(true);
		}
		// Excluding the Summons and Rule Nisi from being stamped for
		// Bibb County (courtUuid)
		if ((docTypeCode == 34) || (docTypeCode == 27)) {
			// We don't stamp with court received stamp but
			// for the time being we mark them as stamped
			this.setStampedDoc(true);
		}
		if ((!((courtUuid.equalsIgnoreCase("courtUuidBibb")) && ((docTypeCode == 34) || (docTypeCode == 27))))
				&& !((courtUuid.equalsIgnoreCase("courtUuid3")) && ((docTypeCode == 34) || docTypeCode == 27))
				&& !((courtUuid.equalsIgnoreCase("courtUuidHart")) && ((docTypeCode == 34) || docTypeCode == 27))

		) {
			documentInstanceCode = doc.getDocumentInstance().getCode();
			// Set document type variable
			doctype = doc.getDocumentInstance().getCode() + "";
			byte[] originalDocContent = doc.getContent();
			docStatusCode = doc.getStatus().getCode();
			if (doc.getContent() != null) {
				// if doc is not ready to be imported and is not already
				// court received stamped
				if ((docStatusCode != 7) // Prepared for Import
						&& (docStatusCode != 9)) { // Stamped with
					// court received
					// stamp
					if (documentInstanceCode != 181) { // Sheriff's
						// Entry of
						// Service -
						// Filed - Bibb

						// Add Clerk Stamp on the first page of each PDF
						// document
						System.out.println("The pdf document " + doc.getTitle()
								+ " A stamp can be applied");

						int visualCategoryCode = 3; // court stamp
						boolean defaultCourtStampFlag = true;
						VisualMarkCategory visualMarkCategory = this
								.getModelFacade().getVisualCategory(
										visualCategoryCode);
						VisualMark visualMark = this.getModelFacade()
								.getVisualMark(personSigner,
										defaultCourtStampFlag,
										visualMarkCategory);

						String courtStampTarget = visualMark.getVisualTarget();
						byte[] newDocContent = pdfStamper.AddCourtStamp(doc,
								sigIndicatorImage, submittedDate, courtUuid,
								courtStampTarget);
						if (newDocContent != null) {
							doc.setContent(personSigner,newDocContent);
							this.setStampedDoc(true);
						} else {
							this.setStampedDoc(false);
							/*
							 * doc.setContent(originalDocContent);
							 * DocumentStatus ds = new DocumentStatus();
							 * ds.setCode(12);
							 * ds.setDescription("failedCourtReceivedStamp");
							 * doc.setStatus(ds);
							 */
						}
					}
				}
			}
		}
	}

	/*
	 * Method to add a Docket ID/Civil Action File Number to a legal document
	 * which has been accepted by the court.
	 * 
	 * public void addDocketID(Documents doc, String docketID, Person
	 * personSigner) { / Read in the pdf file's content and create a temp file
	 * with corresponding title
	 * 
	 * byte[] docContent = doc.getContent(); String caseNumberTarget = "";
	 * boolean altSigFlag = true;
	 * 
	 * int visualCategoryCode = 5; //for Docket ID VisualMarkCategory
	 * visualCategory =
	 * this.getModelFacade().getVisualCategory(visualCategoryCode); VisualMark
	 * visualMark = this.getModelFacade().getVisualMark(personSigner,
	 * altSigFlag, visualCategory);
	 * 
	 * List<String> targetForDocketList = new ArrayList<String>();
	 * List<VisualMark> visualMarkList = new ArrayList<VisualMark>(); // to get
	 * alternet targets set altSigFlag = false visualMarkList =
	 * this.getModelFacade().getVisualMarkList(personSigner, false,
	 * visualCategory);
	 * 
	 * String tempTarget = ""; for (VisualMark vm : visualMarkList) { tempTarget
	 * = vm.getVisualTarget(); targetForDocketList.add(tempTarget); }
	 * caseNumberTarget = visualMark.getVisualTarget();
	 * 
	 * 
	 * byte[] tempDocContents = pdfStamper.addVisualDocketID(doc,
	 * caseNumberTarget, docketID); if (tempDocContents == null) { for (String
	 * targetForSigFromList : targetForDocketList) { tempDocContents =
	 * pdfStamper.addVisualDocketID(doc, caseNumberTarget, docketID); if
	 * (tempDocContents != null) break; } }
	 * 
	 * if (tempDocContents == null) { doc.setContent(docContent); DocumentStatus
	 * ds = new DocumentStatus(); this.getModelFacade().findDocumentStatus(10);
	 * doc.setStatus(ds); return; } else if (tempDocContents != null) {
	 * doc.setContent(tempDocContents); this.setStampedDoc(true); DocumentStatus
	 * ds = new DocumentStatus(); ds.setCode(8);
	 * ds.setDescription("signedByClerk"); doc.setStatus(ds); } }
	 */
	
	
	public Image retrieveSignatureImageFromDB(String personUuid) {
		
		Image image = null;

		SignatureImage signatureImage = this.getModelFacade().findImageByUuid(personUuid); 
		
		try {
			image = Image.getInstance(signatureImage.getImage());
		} catch (BadElementException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}


		return image;
	}
}
